package com.huang.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.extension.exceptions.ApiException;
import com.huang.bo.AreaTaskBo;
import com.huang.common.utils.IdGenerator;
import com.huang.entity.AreaTask;
import com.huang.enums.ResultStatus;
import com.huang.mapper.AreaTaskMapper;
import com.huang.other.AreaTaskListener;
import com.huang.service.AreaTaskDetailService;
import com.huang.service.AreaTaskService;
import com.huang.vo.ResultObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import java.io.IOException;
import java.io.InputStream;

@RequestMapping("/areaTask")
@RestController
public class AreaTaskController {
    private final Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    AreaTaskService areaTaskService;
    @Autowired
    AreaTaskDetailService areaTaskDetailService;

    @Autowired
    AreaTaskMapper areaTaskMapper;
//    @Transactional
    @PostMapping("/addTask")
    public ResultObject addTask(MultipartFile file){
        String userId = "1";
        long taskId = IdGenerator.snowflakeId();
        AreaTask areaTask = new AreaTask();
        areaTask.setTaskId(taskId).setUserId(userId);
        areaTaskService.save(areaTask);
//        if (3>2){
//            throw new ApiException("抛出异常");
//        }
        try (InputStream is = file.getInputStream()) {
            AreaTaskListener areaTaskListener = new AreaTaskListener(taskId,areaTaskDetailService);
            EasyExcel.read(is, AreaTaskBo.class ,areaTaskListener).sheet().doRead();
        } catch (IOException e) {
            logger.error("任务创建失败");
            return ResultObject.fail(ResultStatus.SYS_NEED_RETRY);
        }
        return ResultObject.success(true);
    }

    @Transactional
    @PostMapping("/testTask")
    public ResultObject testTask(MultipartFile file) throws MissingServletRequestParameterException {
        String userId = "1";
        long taskId = IdGenerator.snowflakeId();
        AreaTask areaTask = new AreaTask();
        areaTask.setTaskId(taskId).setUserId(userId);
        areaTaskService.save(areaTask);

        return ResultObject.success(true);
    }

    @GetMapping("/addTask1")
    public void addTask1(){
        areaTaskMapper.insert(new AreaTask().setUserId("1"));
    }

    @GetMapping("/getAreaById")
    public AreaTask getAreaById(int id){
        AreaTask areaTask = areaTaskMapper.getAreaById(id);
        AreaTask byId = areaTaskService.getById(id);
        return areaTask;
    }


}
